package cn.keniykey.mc.landterritory.landflag.flag;

import java.util.Arrays;

import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.hanging.HangingBreakByEntityEvent;

import cn.keniykey.mc.landterritory.config.LanguageManager;
import cn.keniykey.mc.landterritory.event.LandTerritoryReloadConfigEvent;
import cn.keniykey.mc.landterritory.land.api.ILandManager;
import cn.keniykey.mc.landterritory.land.api.Land;
import cn.keniykey.mc.landterritory.landflag.api.ELandFlagParType;
import cn.keniykey.mc.landterritory.landflag.api.ELandFlagType;
import cn.keniykey.mc.landterritory.landflag.api.JavaLandFlag;
import cn.keniykey.mc.landterritory.landflag.api.LandFlagConfigurationFile;
import cn.keniykey.mc.landterritory.landflag.api.LandFlagListenerManager;
import cn.keniykey.mc.landterritory.toolkit.Util;

public final class BanBreakFlag extends JavaLandFlag implements Listener{
	private String tip;
	
	@Override
	public ELandFlagParType getELandFlagParType() {
		return ELandFlagParType.MUCH;
	}
	@Override
	public ELandFlagType getELandFlagType() {
		return ELandFlagType.PLAYER;
	}
	@Override
	public boolean allowAllPlayerData() {
		return false;
	}
	
	@Override
	public void onEnable() {
		LandFlagListenerManager.registerListener(this, this);
	}
	@EventHandler
	public void onConfigLoad(final LandTerritoryReloadConfigEvent e) {
		final LandFlagConfigurationFile config = this.getLandFlagConfigurationFile();
		if(!config.has()) {
			config.set("name", "禁止破坏方块/挂画");
			config.set("lore", Arrays.asList("&7（禁止玩家破坏领地内的方块/挂画）","&5（标记参数为许可玩家）"));
			config.set("tip", "&c没有领地许可，不可以破坏方块/挂画");
		}
		this.setDisplayName(Util.conver(config.getString("name")));
		this.setIntroductionLore(Util.conver(config.getStringList("lore")));
		this.tip = LanguageManager.getChatPrefix() + Util.conver(config.getString("tip"));
	}
	
	@EventHandler(priority = EventPriority.LOW,ignoreCancelled = true)
	public void onBlockBreakEvent(final BlockBreakEvent e) {
		this.onCancellable(e.getPlayer(), e.getBlock().getLocation(), e);
	}
	@EventHandler(priority = EventPriority.LOW,ignoreCancelled = true)
	public void onHangingBreakByEntity(final HangingBreakByEntityEvent e) {
		if (e.getRemover() == null || !(e.getRemover() instanceof Player)) return;
		this.onCancellable((Player)e.getRemover(), e.getEntity().getLocation(), e);
	}
	private void onCancellable(final Player player,final Location loc,final Cancellable able) {
		final Land land = ILandManager.getILandManager().getHighestPriorityLand(loc);
		if(land == null) return;
		if(JavaLandFlag.hasLandFlagParameterAllMethod(land, this, player)) return;
		able.setCancelled(true);
		player.sendMessage(this.tip);
	}
}